package com.midian.common.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.midian.common.exception.BizException;
import com.midian.common.system.SysStatic;
import com.midian.model.pic.Pic;
import com.midian.service.pic.IPicService;

/**
 * 图片操作帮助类
 * @author 飞
 *
 */
@Component("picUtils")
public class PicUtils {
	/**日志对象*/
	private static final Logger LOG = LoggerFactory.getLogger(PicUtils.class);
	/**图片业务*/
	private IPicService picService;
	
	@Resource(name="picService")
	public void setPicService(IPicService picService) {
		this.picService = picService;
	}


	/**
	 * 根据文件类型获取文件流
	 * @param fileObj 文件对象
	 * @return
	 * @throws IOException
	 */
	private InputStream getInputStream(Object fileObj) throws IOException {
		InputStream in = null;
		if(fileObj instanceof File) {
			in = new FileInputStream((File) fileObj);
		} else {
			in = ((MultipartFile) fileObj).getInputStream();
		}
		return in;
	}
	
	
	/**
	 * 上传图片，生成图片记录
	 * @param is 文件输入流
	 * @param fileName 文件名称
	 * @return
	 */
	private Pic createPic(Object fileObj, String fileName) throws BizException {
		FUtil fUtil = new FUtil();
		// 上传的图片列表		
		String picId = "";
		try {
			Pic pic = new Pic();
			String picSuffix = StringUtil.getFileSuffix(fileName).toLowerCase();
			pic.setSuffix(picSuffix);
			picService.add(pic);
			picId = pic.getId();
			fUtil.uploadFile(FUtil.BUCKET_NAME, picId, picSuffix, getInputStream(fileObj));
			return pic;
		} catch (Exception e) {
			LOG.error("[PicUtils/uploadPic]" + e.getMessage());
			e.printStackTrace();
			// 删除图片，抛出异常
			if(StringUtil.isNotEmpty(picId)){
				fUtil.deleteFile(picId);
                picService.delete(picId);				
			}
			throw new BizException(e.getMessage());
		}
	}
	

	/**
	 * 上传一张图片（SpringMVC上传的文件）
	 * @param file 图片文件
	 * @param isPicThumb 是否生成缩略图
	 * @return
	 * @throws Exception
	 */
	public Pic uploadPic(MultipartFile file) throws BizException {
		Pic pic = null;
		try {
			String fileName = file.getOriginalFilename();
			pic = createPic(file, fileName);
		} catch (BizException e) {
			LOG.error(e.getMessage());
		}
		return pic;
	}
	

	
	/**
	 * 上传一张图片（远程资源）
	 * @param url
	 * @return
	 */
	public Pic uploadPicByUrl(String url) {
		Pic pic = null;
		File dir = new File(SysStatic.TEMP_FILE_PATH);
		if(!dir.exists() || !dir.isDirectory()) {
			dir.mkdirs();
		}
		File tempFile = new File(SysStatic.TEMP_FILE_PATH, System.currentTimeMillis() + ".jpg");
		try {
			FileUtils.copyURLToFile(new URL(url), tempFile);
			pic = createPic(tempFile, tempFile.getName());
		} catch (Exception e) {
			LOG.error(e.getMessage());
		} finally {
			tempFile.delete(); //删除本地文件
		}
		return pic;
	}
	
	/**
	 * 删除图片
	 * @param picId
	 */
	public void deletePic(String picId){
		try {
			FUtil fUtil = new FUtil();
			// 删除原图
			Pic pic = picService.get(picId);
			if (pic != null) {// 如果不为空删除旧图片
				fUtil.deleteFile(pic.getId());
			}
			picService.delete(picId);
			
		} catch (BizException e) {
			LOG.error("[PicUtils/deletePic]" + e.getMessage());
		}
	}
	

	
	/**
	 * 更新无缩略图的图片
	 * @param picId 原图片id
	 * @param file 新的图片文件
	 */
	public Pic updatePic(String picId, Object file) throws Exception {
		String picSuffix = "";
		Pic pic = null;
		try {
			FUtil fUtil = new FUtil();
			// 删除原图
			pic = picService.get(picId);
			if (pic != null) {// 如果不为空删除旧图片
				fUtil.deleteFile(pic.getId());
				picService.delete(pic.getId());
			}
			String fileName = "";
			if(file instanceof MultipartFile) {
				fileName = ((MultipartFile) file).getOriginalFilename();
			} else if(file instanceof File) {
				fileName = ((File)file).getName();
			}
			picSuffix = StringUtil.getFileSuffix(fileName).toLowerCase();
			//数据库新增记录
			pic = new Pic();
			pic.setSuffix(picSuffix);
			pic = picService.add(pic);
			//上传图片
			fUtil.uploadFile(FUtil.BUCKET_NAME, pic.getId(), picSuffix, getInputStream(file));
		} catch (BizException e) {
			LOG.error("[PicUtils/updatePic]" + e.getMessage());
		}
		return pic;
	}
	
}
